using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
using Yoozoo.Managers.ResourceManagerV2.Runtime;

public class CarResLoader : MonoBehaviour
{
    /// <summary>
    /// 不太信任lua持有loader
    /// 感觉很容易被GC或者什么的
    /// </summary>
    private ResLoader m_resLoader;
    private Dictionary<string, GameObject> m_resMapper;
    private void Awake()
    {
        m_resMapper = new Dictionary<string, GameObject>();
        m_resLoader = ResLoader.Alloc();
        m_resLoader.forceRelease = true;
    }
    
    [LuaCallCSharp]
    public void InstantiateObjectPart(string tag,string resPath,Action<GameObject> onResLoaded)
    {
        if (m_resMapper.ContainsKey(tag))
        {
            onResLoaded?.Invoke(m_resMapper[tag]);
            return;
        }
        
        m_resLoader.Add2Load(resPath, typeof(GameObject), ((success, name, asset) =>
        {
            GameObject tmp = asset as GameObject;
            
            if (!m_resMapper.ContainsKey(tag))
            {
                GameObject instObj = Instantiate(tmp, transform);
                m_resMapper.Add(tag, instObj);
                onResLoaded?.Invoke(instObj);
            }
        }));
        m_resLoader.Load();
    }
    
    [LuaCallCSharp]
    public GameObject GetObjectPartByTag(string tag)
    {
        if (m_resMapper.ContainsKey(tag))
        {
            return m_resMapper[tag];
        }

        return null;
    }
    
    private void OnDestroy()
    {
        m_resLoader?.ReleaseAllRes();
        m_resLoader?.Recycle2Cache();
        m_resLoader = null;
    }
}